import Cookies from 'js-cookie'
import store from '../store'
import { Message } from 'element-ui'

const TokenKey = 'vue_admin_template_token'
const CookieKey = 'vue_admin_template_cookie'
const result = new Map()

export function getToken() {
  return Cookies.get(TokenKey)
}

export function getCookie() {
  return Cookies.get(CookieKey)
}

export function setToken(token, cookie) {
  Cookies.set(CookieKey, cookie)
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export const checkClick = (mark = null, abnormal = true) => {
  const uriList = store.getters.staffAuth
  let uri = null
  if (uriList !== null) {
    if (uriList[mark]) {
      if (uriList[mark]['pid'] > 0) {
        uri = findIsBuy(uriList[mark]['pid'], uriList)
        if (uri['pid'] !== 0) {
          uri = false
        }
      } else {
        uri = uriList[mark]
      }
    } else {
      uri = false
    }
  } else {
    uri = { 'deadline': null }
  }
  if (mark === null || uri === null || uri['is_buy'] === 0 || (uri['deadline'] && uri['deadline']['surplus_day'] > 0)) {
    return true
  } else {
    if (uri === false && abnormal) {
      Message.error('没有该权限，请找主账号授权')
    } else if (uri['is_buy'] && uri['deadline'] === null && abnormal) {
      Message.error('没有购买该权限，请购买后使用')
    } else if (uri['is_buy'] && (uri['deadline'] && uri['deadline']['surplus_day'] <= 0) && abnormal) {
      Message.error('该功能已过期，请续费后使用')
    }
    return false
  }
}

export const hasScope = function(key) {
  if (result.has(key)) {
    return result.get(key)
  } else {
    result.set(key, checkClick(key, false))
    return result.get(key)
  }
}

// 查找父级项目
function findIsBuy(id, lists) {
  for (const key in lists) {
    /* eslint-disable */
    if (lists.hasOwnProperty(key)) {
      const item = lists[key]
      if (item !== null && id === item['menu_id']) {
        if (item['pid'] !== 0) {
          return findIsBuy(item['pid'], lists)
        } else {
          return item
        }
      }
    }
  }
}
